import Router from 'koa-router'
import app from '../app'
import { Methods } from '.'


export function controller(root: string) {
  console.log(root)
    const router = new Router({ prefix: root })
    app.use(router.routes()).use(router.allowedMethods())
    return function (target: new (...args: any[]) => any) {
      for (const key in target.prototype) {
        const path: string = Reflect.getMetadata('path', target.prototype, key)
        const middlewares: any[] = Reflect.getMetadata(
          'middlewares',
          target.prototype,
          key
        )
        const method: Methods = Reflect.getMetadata(
          'method',
          target.prototype,
          key
        )
        const handler = target.prototype[key]
        if (path && method) {
          if (middlewares && middlewares.length) {
            router[method](path, ...middlewares, handler)
          } else {
            router[method](path, handler)
          }
        }
      }
    }
  }